package com.yeren.servlet.tarena.emp;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yeren.servlet.tarena.dao.EmployeeDAO;
import com.yeren.servlet.tarena.entity.Employee;



public class ActionServlet extends HttpServlet {
	/*
	 * 使用请求中的name,contact两组参数值 分别使用getParameter和getParameterValues方法获取
	 */
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter out = resp.getWriter();
		
		//
		String uri=req.getRequestURI();
		//
		String action=uri.substring(uri.lastIndexOf("/")+1,uri.lastIndexOf("."));
		if(action.equals("list")){
			try{
				EmployeeDAO dao=new EmployeeDAO();
				List<Employee> emps=dao.findAll();
				out.println("<table border='1' align='center'>" );
				out.println("<caption>员工信息列表</caption>");
				out.println("<tr><td>编号</td><td>姓名</td><td>薪水</td><td>年龄</td><td>操作</td></tr>");
				for(Employee emp:emps){
					out.println("<tr>");
					out.println("<td>"+emp.getId()+"</td>");
					out.println("<td>"+emp.getName()+"</td>");
					out.println("<td>"+emp.getSalary()+"</td>");
					out.println("<td>"+emp.getAge()+"</td>");
					out.println("<td><a href='#'>删除</a><a href='#'>修改</a></td>");
					out.println("</tr>");
				}
				out.println("</table>");
				out.println("<p align='center'><a href='addEmp.html'>增加新员工</a></p>");
			}catch(Exception e){
				e.printStackTrace();
				out.print("系统繁忙");
			}
		}else if(action.equals("add")){
			String name=req.getParameter("name");
			double salary=Double.parseDouble(req.getParameter("salary"));
			int age=Integer.parseInt(req.getParameter("age"));
			try{
				Employee emp=new Employee();
				emp.setName(name);
				emp.setSalary(salary);
				emp.setAge(age);
				EmployeeDAO dao=new EmployeeDAO();
				dao.save(emp);
				resp.sendRedirect("list.do");
			}catch(Exception e){
				e.printStackTrace();
				out.print("系统繁忙");
			}
		}
	}
}
